#include "SmeltingConfigWidget.h"
#include <QApplication>
#include <QPainter>
#include <QDebug>
#include <QPixmap>
#include <QFont>

SmeltingConfigWidget::SmeltingConfigWidget(QWidget *parent)
    : QWidget(parent)
    , m_isEditMode(false)
    , m_currentStoveIndex(0)
{
    setupUI();
    setupConnections();
    loadDataForStove(0);
}

SmeltingConfigWidget::~SmeltingConfigWidget()
{
}

void SmeltingConfigWidget::setupUI()
{
    setStyleSheet("background: transparent;");
    
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(20);

    QGridLayout *gridLayout = new QGridLayout();
    gridLayout->setSpacing(15);
    gridLayout->setContentsMargins(0, 0, 0, 0);
    
    gridLayout->setColumnStretch(0, 1);
    gridLayout->setColumnStretch(1, 1);
    gridLayout->setRowStretch(0, 1);
    gridLayout->setRowStretch(1, 1);

    setupWorkingConditionPanel();
    setupOxygenLancePanel();
    setupMaterialPanel();
    setupOtherPanel();

    gridLayout->addWidget(m_workingConditionPanel, 0, 0);
    gridLayout->addWidget(m_oxygenLancePanel, 0, 1);
    gridLayout->addWidget(m_materialPanel, 1, 0);
    gridLayout->addWidget(m_otherPanel, 1, 1);

    m_mainLayout->addLayout(gridLayout);

    setupBottomButtons();
}

void SmeltingConfigWidget::setupWorkingConditionPanel()
{
    m_workingConditionPanel = new ConfigItemWidget("工况类");
    m_workingConditionPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    m_workingConditionPanel->addConfigItem("铁水Mn", ConfigItemWidget::LineEdit, "", 0, 0);
    m_workingConditionPanel->addConfigItem("铁水P", ConfigItemWidget::LineEdit, "", 0, 2);
    m_workingConditionPanel->addConfigItem("铁水S", ConfigItemWidget::LineEdit, "", 0, 4);
    m_workingConditionPanel->addConfigItem("铁水Ti", ConfigItemWidget::LineEdit, "", 0, 6);
    m_workingConditionPanel->addConfigItem("铁水其他", ConfigItemWidget::LineEdit, "", 0, 8);

    m_workingConditionPanel->addConfigItem("目标C", ConfigItemWidget::LineEdit, "", 1, 0);
    m_workingConditionPanel->addConfigItem("目标Si", ConfigItemWidget::LineEdit, "", 1, 2);
    m_workingConditionPanel->addConfigItem("目标Mn", ConfigItemWidget::LineEdit, "", 1, 4);
    m_workingConditionPanel->addConfigItem("目标P", ConfigItemWidget::LineEdit, "", 1, 6);
    m_workingConditionPanel->addConfigItem("目标S", ConfigItemWidget::LineEdit, "", 1, 8);

    m_workingConditionPanel->addConfigItem("目标T", ConfigItemWidget::LineEdit, "", 2, 0);

    m_workingConditionPanel->addConfigItem("废钢C", ConfigItemWidget::LineEdit, "", 3, 0);
    m_workingConditionPanel->addConfigItem("废钢Si", ConfigItemWidget::LineEdit, "", 3, 2);
    m_workingConditionPanel->addConfigItem("废钢Mn", ConfigItemWidget::LineEdit, "", 3, 4);
    m_workingConditionPanel->addConfigItem("铁氧化", ConfigItemWidget::LineEdit, "", 3, 6);

    m_workingConditionPanel->addConfigItem("正常溢渣", ConfigItemWidget::LineEdit, "", 4, 0);
    m_workingConditionPanel->addMultiConfigItem("留渣量", {"全留", "多留", "少留", "不留"}, 
                                               {"", "", "", ""}, 4, 2);
    m_workingConditionPanel->addStretch();
}

void SmeltingConfigWidget::setupOxygenLancePanel()
{
    m_oxygenLancePanel = new ConfigItemWidget("氧枪类");
    m_oxygenLancePanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 氧枪划分
    QStringList lanceStageKeys = {"@stage1", "@stage2", "@stage3", "@stage4", "@stage5", "@stage6"};
    m_oxygenLancePanel->addMultiConfigItem("氧枪划分", lanceStageKeys,
                                           QStringList(lanceStageKeys.size(), ""), 0, 0);

    // 第二行
    m_oxygenLancePanel->addConfigItem("真实氧流量", ConfigItemWidget::LineEdit, "", 1, 0);
    m_oxygenLancePanel->addConfigItem("后吹氧利用率", ConfigItemWidget::LineEdit, "", 1, 2);
    m_oxygenLancePanel->addMultiConfigItem("初始耗氧因子", {"A", "B"}, {"", ""}, 1, 5);

    // 第三行
    m_oxygenLancePanel->addConfigItem("烧结矿品位", ConfigItemWidget::LineEdit, "", 2, 0);
    m_oxygenLancePanel->addConfigItem("焦丁中碳含量", ConfigItemWidget::LineEdit, "", 2, 2);
    m_oxygenLancePanel->addConfigItem("石灰石CO2含量", ConfigItemWidget::LineEdit, "", 2, 5);

    // 第四行 - 提供氧量
    m_oxygenLancePanel->addMultiConfigItem("提供氧量", {"烧结矿", "钢渣", "焦丁", "石灰石"}, {"", "", "", ""}, 3, 0);

    // 第五行
    m_oxygenLancePanel->addConfigItem("调整铁水C上限", ConfigItemWidget::LineEdit, "450", 4, 0);
    m_oxygenLancePanel->addConfigItem("调节比例", ConfigItemWidget::LineEdit, "", 4, 3);
    m_oxygenLancePanel->addStretch();
}

void SmeltingConfigWidget::setupMaterialPanel()
{
    m_materialPanel = new ConfigItemWidget("物料类");
    m_materialPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    m_materialPanel->addConfigItem("投料模式", ConfigItemWidget::LineEdit, "", 0, 0);
    m_materialPanel->addMultiConfigItem("投料参数", {"CSJK", "GSJK"}, {"", ""}, 0, 2);

    m_materialPanel->addRowStretch(0, 9);
    m_materialPanel->addStretch();
}

void SmeltingConfigWidget::setupOtherPanel()
{
    m_otherPanel = new ConfigItemWidget("其他");
    m_otherPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_otherPanel->addStretch();
}

void SmeltingConfigWidget::setupBottomButtons()
{
    m_bottomLayout = new QHBoxLayout();
    m_bottomLayout->setContentsMargins(0, 0, 24, 0);
    m_bottomLayout->setSpacing(10);
    m_bottomLayout->addStretch();
    
    m_bottomLayout->addStretch();
    
    m_editButton = new QPushButton("编辑");
    m_editButton->setFixedSize(100, 40);
    m_editButton->setObjectName("activableButton");
    
    m_submitButton = new QPushButton("提交");
    m_submitButton->setFixedSize(100, 40);
    m_submitButton->setEnabled(false);
    m_submitButton->setObjectName("activableButton");
    
    m_bottomLayout->addWidget(m_editButton);
    m_bottomLayout->addWidget(m_submitButton);
    
    m_mainLayout->addLayout(m_bottomLayout);
}

void SmeltingConfigWidget::setupConnections()
{
    connect(m_editButton, &QPushButton::clicked, this, &SmeltingConfigWidget::onEditButtonClicked);
    connect(m_submitButton, &QPushButton::clicked, this, &SmeltingConfigWidget::onSubmitButtonClicked);
    
    // 连接数据变化信号
    if (m_workingConditionPanel) {
        connect(m_workingConditionPanel, &ConfigItemWidget::valueChanged,
                this, &SmeltingConfigWidget::onWorkingConditionValueChanged);
    }
    if (m_oxygenLancePanel) {
        connect(m_oxygenLancePanel, &ConfigItemWidget::valueChanged,
                this, &SmeltingConfigWidget::onOxygenLanceValueChanged);
    }
    if (m_materialPanel) {
        connect(m_materialPanel, &ConfigItemWidget::valueChanged,
                this, &SmeltingConfigWidget::onMaterialValueChanged);
    }
}

void SmeltingConfigWidget::onEditButtonClicked()
{
    m_isEditMode = !m_isEditMode;
    
    if (m_isEditMode) {
        m_editButton->setText("取消");
        m_submitButton->setEnabled(true);
        
        setEditMode(true);
    } else {
        m_editButton->setText("编辑");
        m_submitButton->setEnabled(false);
        
        setEditMode(false);
    }
    
    qDebug() << "Edit mode:" << m_isEditMode;
}

void SmeltingConfigWidget::onSubmitButtonClicked()
{
    qDebug() << "Submit button clicked";
    
    // 获取所有配置项的值
    qDebug() << "Working Condition Panel Values:";
    qDebug() << "铁水Mn:" << m_workingConditionPanel->getValue("铁水Mn");
    qDebug() << "目标C:" << m_workingConditionPanel->getValue("目标C");
    qDebug() << "留渣量:" << m_workingConditionPanel->getValue("留渣量");
    
    qDebug() << "Oxygen Lance Panel Values:";
    qDebug() << "真实氧流量:" << m_oxygenLancePanel->getValue("真实氧流量");
    qDebug() << "烧结矿:" << m_oxygenLancePanel->getValue("烧结矿");
    
    qDebug() << "Material Panel Values:";
    qDebug() << "烧结矿量:" << m_materialPanel->getValue("烧结矿量");
    
    m_isEditMode = false;
    m_editButton->setText("编辑");
    m_submitButton->setEnabled(false);
    setEditMode(false);
}

void SmeltingConfigWidget::setEditMode(bool enabled)
{
    if (m_workingConditionPanel) {
        m_workingConditionPanel->setEditMode(enabled);
    }
    if (m_oxygenLancePanel) {
        m_oxygenLancePanel->setEditMode(enabled);
    }
    if (m_materialPanel) {
        m_materialPanel->setEditMode(enabled);
    }
    if (m_otherPanel) {
        m_otherPanel->setEditMode(enabled);
    }
}

static NavTreeIndex configIndexForStove(int stoveIndex)
{
    switch (stoveIndex) {
    case 0: return NavTreeIndex::Config_1;
    case 1: return NavTreeIndex::Config_2;
    case 2: return NavTreeIndex::Config_3;
    case 3: return NavTreeIndex::Config_4;
    case 4: return NavTreeIndex::Config_5;
    case 5: return NavTreeIndex::Config_6;
    default: return NavTreeIndex::Config_1;
    }
}

void SmeltingConfigWidget::loadDataForStove(int stoveIndex)
{
    m_currentStoveIndex = stoveIndex;
    
    auto format = [](double value, int precision = 2) {
        return QString::number(value, 'f', precision);
    };

    NavTreeIndex configIndex = configIndexForStove(stoveIndex);
    NavTreeIndex oxygenIndex = static_cast<NavTreeIndex>(static_cast<int>(configIndex) + 1);
    NavTreeIndex materialIndex = static_cast<NavTreeIndex>(static_cast<int>(configIndex) + 2);

    if (m_workingConditionPanel) {
        ConfigWorkingConditionData workingData;
        if (SteelClientData::getWorkingConditionData(configIndex, workingData)) {
            m_workingConditionPanel->setValue("铁水Mn", format(workingData.moltenIron.Mn));
            m_workingConditionPanel->setValue("铁水P", format(workingData.moltenIron.P));
            m_workingConditionPanel->setValue("铁水S", format(workingData.moltenIron.S));
            m_workingConditionPanel->setValue("铁水Ti", format(workingData.moltenIron.Ti));
            m_workingConditionPanel->setValue("铁水其他", format(workingData.moltenIron.other));

            m_workingConditionPanel->setValue("目标C", format(workingData.target.C));
            m_workingConditionPanel->setValue("目标Si", format(workingData.target.Si));
            m_workingConditionPanel->setValue("目标Mn", format(workingData.target.Mn));
            m_workingConditionPanel->setValue("目标P", format(workingData.target.P));
            m_workingConditionPanel->setValue("目标S", format(workingData.target.S));
            m_workingConditionPanel->setValue("目标T", format(workingData.target.T, 0));

            m_workingConditionPanel->setValue("废钢C", format(workingData.scrapSteel.C));
            m_workingConditionPanel->setValue("废钢Si", format(workingData.scrapSteel.Si));
            m_workingConditionPanel->setValue("废钢Mn", format(workingData.scrapSteel.Mn));
            m_workingConditionPanel->setValue("铁氧化", format(workingData.scrapSteel.oxidation));

            m_workingConditionPanel->setValue("正常溢渣", format(workingData.chuteFlow.normal));
            m_workingConditionPanel->setValue("全留", format(workingData.chuteFlow.retain));
            m_workingConditionPanel->setValue("多留", format(workingData.chuteFlow.more));
            m_workingConditionPanel->setValue("少留", format(workingData.chuteFlow.less));
            m_workingConditionPanel->setValue("不留", format(workingData.chuteFlow.none));
        } else {
            QStringList keys = {"铁水Mn", "铁水P", "铁水S", "铁水Ti", "铁水其他",
                                "目标C", "目标Si", "目标Mn", "目标P", "目标S", "目标T",
                                "废钢C", "废钢Si", "废钢Mn", "铁氧化",
                                "正常溢渣", "全留", "多留", "少留", "不留"};
            for (const QString& key : keys) {
                m_workingConditionPanel->setValue(key, "");
            }
        }
    }

    if (m_oxygenLancePanel) {
        ConfigOxygenLanceData oxygenData;
        if (SteelClientData::getOxygenLanceData(oxygenIndex, oxygenData)) {
            QStringList lanceStageKeys = {"@stage1", "@stage2", "@stage3", "@stage4", "@stage5", "@stage6"};
            for (int i = 0; i < lanceStageKeys.size(); ++i) {
                m_oxygenLancePanel->setValue(lanceStageKeys[i], format(oxygenData.lanceDivision[i], 0));
            }

            m_oxygenLancePanel->setValue("真实氧流量", format(oxygenData.actualOxygenFlow, 0));
            m_oxygenLancePanel->setValue("后吹氧利用率", format(oxygenData.postBlowOxygenUtilization));
            m_oxygenLancePanel->setValue("A", format(oxygenData.initialOxygenFactor.A));
            m_oxygenLancePanel->setValue("B", format(oxygenData.initialOxygenFactor.B));

            m_oxygenLancePanel->setValue("烧结矿品位", format(oxygenData.sinteredOreGrade));
            m_oxygenLancePanel->setValue("焦丁中碳含量", format(oxygenData.cokeBreezeCarbonContent));
            m_oxygenLancePanel->setValue("石灰石CO2含量", format(oxygenData.limestoneCO2Content));

            m_oxygenLancePanel->setValue("烧结矿", format(oxygenData.oxygenSupply.sinter, 0));
            m_oxygenLancePanel->setValue("钢渣", format(oxygenData.oxygenSupply.steel, 0));
            m_oxygenLancePanel->setValue("焦丁", format(oxygenData.oxygenSupply.coke, 0));
            m_oxygenLancePanel->setValue("石灰石", format(oxygenData.oxygenSupply.limestone, 0));

            m_oxygenLancePanel->setValue("调整铁水C上限", format(oxygenData.adjustMoltenIronCUpperLimit));
            m_oxygenLancePanel->setValue("调节比例", format(oxygenData.adjustmentRatio));
        } else {
            QStringList keys = {"@stage1", "@stage2", "@stage3", "@stage4", "@stage5", "@stage6",
                                "真实氧流量", "后吹氧利用率", "A", "B",
                                "烧结矿品位", "焦丁中碳含量", "石灰石CO2含量",
                                "烧结矿", "钢渣", "焦丁", "石灰石",
                                "调整铁水C上限", "调节比例"};
            for (const QString& key : keys) {
                m_oxygenLancePanel->setValue(key, "");
            }
        }
    }

    if (m_materialPanel) {
        ConfigMaterialData materialData;
        if (SteelClientData::getMaterialData(materialIndex, materialData)) {
            m_materialPanel->setValue("投料模式", QString::number(materialData.feedingMode.mode));
            m_materialPanel->setValue("CSJK", format(materialData.feedingMode.csjk));
            m_materialPanel->setValue("GSJK", format(materialData.feedingMode.gsjk));
        } else {
            m_materialPanel->setValue("投料模式", "");
            m_materialPanel->setValue("CSJK", "");
            m_materialPanel->setValue("GSJK", "");
        }
    }
}

double SmeltingConfigWidget::parseDouble(const QString &str) const
{
    bool ok;
    double value = str.toDouble(&ok);
    return ok ? value : 0.0;
}

int SmeltingConfigWidget::parseInt(const QString &str) const
{
    bool ok;
    int value = str.toInt(&ok);
    return ok ? value : 0;
}

void SmeltingConfigWidget::onWorkingConditionValueChanged(const QString &name, const QString &value)
{
    if (!m_isEditMode) {
        return; // 只在编辑模式下更新数据
    }
    
    Q_UNUSED(name);
    Q_UNUSED(value);
    
    // 延迟更新，避免在快速输入时频繁触发回调
    updateWorkingConditionData();
}

void SmeltingConfigWidget::onOxygenLanceValueChanged(const QString &name, const QString &value)
{
    if (!m_isEditMode) {
        return; // 只在编辑模式下更新数据
    }
    
    Q_UNUSED(name);
    Q_UNUSED(value);
    
    // 延迟更新，避免在快速输入时频繁触发回调
    updateOxygenLanceData();
}

void SmeltingConfigWidget::onMaterialValueChanged(const QString &name, const QString &value)
{
    if (!m_isEditMode) {
        return; // 只在编辑模式下更新数据
    }
    
    Q_UNUSED(name);
    Q_UNUSED(value);
    
    // 延迟更新，避免在快速输入时频繁触发回调
    updateMaterialData();
}

void SmeltingConfigWidget::updateWorkingConditionData()
{
    if (!m_workingConditionPanel) {
        return;
    }
    
    NavTreeIndex configIndex = configIndexForStove(m_currentStoveIndex);
    
    // 获取当前数据（如果有的话）
    ConfigWorkingConditionData data;
    SteelClientData::getWorkingConditionData(configIndex, data);
    
    // 更新数据
    data.moltenIron.Mn = parseDouble(m_workingConditionPanel->getValue("铁水Mn"));
    data.moltenIron.P = parseDouble(m_workingConditionPanel->getValue("铁水P"));
    data.moltenIron.S = parseDouble(m_workingConditionPanel->getValue("铁水S"));
    data.moltenIron.Ti = parseDouble(m_workingConditionPanel->getValue("铁水Ti"));
    data.moltenIron.other = parseDouble(m_workingConditionPanel->getValue("铁水其他"));
    
    data.target.C = parseDouble(m_workingConditionPanel->getValue("目标C"));
    data.target.Si = parseDouble(m_workingConditionPanel->getValue("目标Si"));
    data.target.Mn = parseDouble(m_workingConditionPanel->getValue("目标Mn"));
    data.target.P = parseDouble(m_workingConditionPanel->getValue("目标P"));
    data.target.S = parseDouble(m_workingConditionPanel->getValue("目标S"));
    data.target.T = parseDouble(m_workingConditionPanel->getValue("目标T"));
    
    data.scrapSteel.C = parseDouble(m_workingConditionPanel->getValue("废钢C"));
    data.scrapSteel.Si = parseDouble(m_workingConditionPanel->getValue("废钢Si"));
    data.scrapSteel.Mn = parseDouble(m_workingConditionPanel->getValue("废钢Mn"));
    data.scrapSteel.oxidation = parseDouble(m_workingConditionPanel->getValue("铁氧化"));
    
    data.chuteFlow.normal = parseDouble(m_workingConditionPanel->getValue("正常溢渣"));
    data.chuteFlow.retain = parseDouble(m_workingConditionPanel->getValue("全留"));
    data.chuteFlow.more = parseDouble(m_workingConditionPanel->getValue("多留"));
    data.chuteFlow.less = parseDouble(m_workingConditionPanel->getValue("少留"));
    data.chuteFlow.none = parseDouble(m_workingConditionPanel->getValue("不留"));
    
    // 更新数据并触发回调
    SteelClientData::setWorkingConditionData(configIndex, data);
}

void SmeltingConfigWidget::updateOxygenLanceData()
{
    if (!m_oxygenLancePanel) {
        return;
    }
    
    NavTreeIndex configIndex = configIndexForStove(m_currentStoveIndex);
    NavTreeIndex oxygenIndex = static_cast<NavTreeIndex>(static_cast<int>(configIndex) + 1);
    
    // 获取当前数据（如果有的话）
    ConfigOxygenLanceData data;
    SteelClientData::getOxygenLanceData(oxygenIndex, data);
    
    // 更新氧枪划分
    QStringList lanceStageKeys = {"@stage1", "@stage2", "@stage3", "@stage4", "@stage5", "@stage6"};
    for (int i = 0; i < lanceStageKeys.size() && i < 6; ++i) {
        data.lanceDivision[i] = parseDouble(m_oxygenLancePanel->getValue(lanceStageKeys[i]));
    }
    
    data.actualOxygenFlow = parseDouble(m_oxygenLancePanel->getValue("真实氧流量"));
    data.postBlowOxygenUtilization = parseDouble(m_oxygenLancePanel->getValue("后吹氧利用率"));
    data.initialOxygenFactor.A = parseDouble(m_oxygenLancePanel->getValue("A"));
    data.initialOxygenFactor.B = parseDouble(m_oxygenLancePanel->getValue("B"));
    
    data.sinteredOreGrade = parseDouble(m_oxygenLancePanel->getValue("烧结矿品位"));
    data.cokeBreezeCarbonContent = parseDouble(m_oxygenLancePanel->getValue("焦丁中碳含量"));
    data.limestoneCO2Content = parseDouble(m_oxygenLancePanel->getValue("石灰石CO2含量"));
    
    data.oxygenSupply.sinter = parseDouble(m_oxygenLancePanel->getValue("烧结矿"));
    data.oxygenSupply.steel = parseDouble(m_oxygenLancePanel->getValue("钢渣"));
    data.oxygenSupply.coke = parseDouble(m_oxygenLancePanel->getValue("焦丁"));
    data.oxygenSupply.limestone = parseDouble(m_oxygenLancePanel->getValue("石灰石"));
    
    data.adjustMoltenIronCUpperLimit = parseDouble(m_oxygenLancePanel->getValue("调整铁水C上限"));
    data.adjustmentRatio = parseDouble(m_oxygenLancePanel->getValue("调节比例"));
    
    // 更新数据并触发回调
    SteelClientData::setOxygenLanceData(oxygenIndex, data);
}

void SmeltingConfigWidget::updateMaterialData()
{
    if (!m_materialPanel) {
        return;
    }
    
    NavTreeIndex configIndex = configIndexForStove(m_currentStoveIndex);
    NavTreeIndex materialIndex = static_cast<NavTreeIndex>(static_cast<int>(configIndex) + 2);
    
    // 获取当前数据（如果有的话）
    ConfigMaterialData data;
    SteelClientData::getMaterialData(materialIndex, data);
    
    // 更新数据
    data.feedingMode.mode = parseInt(m_materialPanel->getValue("投料模式"));
    data.feedingMode.csjk = parseDouble(m_materialPanel->getValue("CSJK"));
    data.feedingMode.gsjk = parseDouble(m_materialPanel->getValue("GSJK"));
    
    // 更新数据并触发回调
    SteelClientData::setMaterialData(materialIndex, data);
}
